package com.atguigu.exam.service.impl;

import com.atguigu.exam.entity.Banner;
import com.atguigu.exam.mapper.BannerMapper;
import com.atguigu.exam.service.BannerService;
import com.atguigu.exam.service.FileUploadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 轮播图服务实现类
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {

   @Autowired
    private FileUploadService fileUploadService;

   @Override
    public  String uploadBannerImage(MultipartFile file) throws Exception {
       //非空校验
       if (file == null || file.isEmpty()) {
           throw new RuntimeException("上传轮播图失败！！原因：上传的不能为空！");
       }
       //格式校验
       if (!file.getContentType().startsWith("image")) {
           throw new RuntimeException("上传轮播图失败！！原因：上传的必须是图片文件！");
       }
       //格式校验
       if (!file.getContentType().startsWith("image")) {
           throw new RuntimeException("上传轮播图失败！！原因：上传的文件类型错误,非图片！");
       }
       //调用核心业务员
       String url = fileUploadService.uploadFile("banners", file);
       //4.返回地址
       return url;

   }
    @Override
    public void addBanner(Banner banner) throws Exception {
        //1.检查默认值 isActive = true  sortOrder = 5
        if (banner.getIsActive() == null){
            banner.setIsActive(true);
        }
        if (banner.getSortOrder() == null){
            banner.setSortOrder(5);
        }
        boolean saved = save(banner);
        if (!saved){
            throw new Exception("轮播图数据保存失败！！");
        }
    }
    @Override
    public void updateBanner(Banner banner) throws Exception {
        //1.检查默认值 isActive = true  sortOrder = 5
        if (banner.getIsActive() == null){
            banner.setIsActive(true);
        }
        if (banner.getSortOrder() == null){
            banner.setSortOrder(5);
        }

        //2.调用修改即可
        boolean updated = updateById(banner);
        if (!updated){
            throw new Exception("轮播图修改失败！");
        }
    }

}
